import { service } from '@vimi/utils-api'
// import { cascaderParse } from '@vimi/utils-tool'
const state = {
  industryType: [],
  industryTypeEnum: {},
  provinceMainBusiness: [],
  provinceMainBusinessEnum: {},
  parentMainBusiness: [],
  parentMainBusinessEnum: {},
}

const getters = {
  industryType: state => state.industryType,
  provinceMainBusiness: state => state.provinceMainBusiness,
  provinceMainBusinessEnum: state => state.provinceMainBusinessEnum,
  parentMainBusiness: state => state.parentMainBusiness,
  parentMainBusinessEnum: state => state.parentMainBusinessEnum,
}

const actions = {
  async getIndustryType({ commit }, force = false) {
    if (!force && state.industryType.length) {
      return Promise.resolve(state.casData)
    }
    const res = await service.post(`/api/credit/proxy/`, {
      proxy_key: 'country-ind-match-query',
    })
    const data = res?.data?.auto_data?.classifyMatchList ?? []
    const enumData = data.reduce((a, b) => {
      a[b.code] = b.value
      return a
    }, {})
    // const casData = cascaderParse({
    //   data,
    //   key: 'id',
    //   parentKey: 'parentId',
    //   checkParent: true,
    // })
    commit('industryType', data)
    commit('industryTypeEnum', enumData)
    return data
  },
  async getProvinceMainBusiness({ commit }, force = false) {
    if (!force && state.provinceMainBusiness.length) {
      return Promise.resolve(state.provinceMainBusiness)
    }
    const res = await service.post(`/api/credit/proxy/`, { proxy_key: '12ind-query' })
    const data = res?.data?.auto_data?.productList ?? []
    const enumData = data.reduce((a, b) => {
      a[b.code] = b.value
      return a
    }, {})
    commit('provinceMainBusiness', data)
    commit('provinceMainBusinessEnum', enumData)
    return data
  },
  async getParentMainBusiness({ commit }, force = false) {
    if (!force && state.parentMainBusiness.length) {
      return Promise.resolve(state.parentMainBusiness)
    }
    const res = await service.post(`/api/credit/proxy/`, { proxy_key: 'country-ind-query' })
    const data = res?.data?.auto_data?.countryGuaranteeTypeList ?? []
    const enumData = data.reduce((a, b) => {
      a[b.code] = b.value
      return a
    }, {})
    commit('parentMainBusiness', data)
    commit('parentMainBusinessEnum', enumData)
    return data
  },
}

const mutations = {
  industryType: (state, payload) => (state.industryType = payload),
  industryTypeEnum: (state, payload) => (state.industryTypeEnum = payload),
  provinceMainBusiness: (state, payload) => (state.provinceMainBusiness = payload),
  provinceMainBusinessEnum: (state, payload) => (state.provinceMainBusinessEnum = payload),
  parentMainBusiness: (state, payload) => (state.parentMainBusiness = payload),
  parentMainBusinessEnum: (state, payload) => (state.parentMainBusinessEnum = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
